package com.training.service;

import com.training.entity.Course;
import com.training.entity.PurchaseRecord;
import com.training.entity.Student;
import com.training.mapper.CourseMapper;
import com.training.mapper.PurchaseRecordMapper;
import com.training.mapper.StudentCourseMapper;
import com.training.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal; // 1. Import BigDecimal
import java.util.List;

@Service
public class PurchaseRecordService {

    @Autowired
    private PurchaseRecordMapper purchaseRecordMapper;

    @Autowired
    private CourseService courseService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private StudentCourseMapper studentCourseMapper;

    @Transactional
    public boolean purchaseCourse(Long studentId, Long courseId) {
        if (purchaseRecordMapper.countPurchaseRecord(studentId, courseId) > 0) {
            System.err.println("课程ID " + courseId + " 已被购买，跳过。");
            return false;
        }

        Course course = courseService.getCourseById(courseId);
        if (course == null) throw new RuntimeException("课程不存在，无法购买。");
        Student student = studentService.getStudentById(studentId);
        if (student == null) throw new RuntimeException("学生信息不存在，无法购买。");

        // --- CORE FIX: Use BigDecimal for price and score comparison ---
        // 2. Get the price as a BigDecimal
        BigDecimal coursePrice = course.getCouPrice() != null ? course.getCouPrice() : BigDecimal.ZERO;
        long studentScore = student.getStuScore() != null ? student.getStuScore() : 0L;

        // 3. Compare student's score with the integer value of the price
        if (studentScore < coursePrice.longValue()) {
            System.err.println("学生积分不足，购买失败。");
            return false;
        }

        student.setStuScore(studentScore - coursePrice.longValue());
        studentService.updateStudent(student);

        PurchaseRecord record = new PurchaseRecord();
        record.setStudentId(studentId);
        record.setCourseId(courseId);
        record.setPurchasePrice(coursePrice); // Set the BigDecimal price directly
        record.setDeleted(0);
        purchaseRecordMapper.insertPurchaseRecord(record);

        studentCourseMapper.addCourseToStudent(studentId, courseId);

        return true;
    }

    @Transactional
    public boolean batchPurchaseCoursesFromCart(Long studentId, List<Long> courseIds) {
        if (courseIds == null || courseIds.isEmpty()) {
            return true;
        }

        Student student = studentService.getStudentById(studentId);
        if (student == null) {
            throw new RuntimeException("学生信息不存在，无法购买课程。");
        }

        // --- CORE FIX: Use BigDecimal for total cost calculation ---
        // 4. Change totalCost to BigDecimal
        BigDecimal totalCost = BigDecimal.ZERO;
        for (Long courseId : courseIds) {
            Course course = courseService.getCourseById(courseId);
            if (course != null) {
                // 5. Use the .add() method for accurate addition
                if(course.getCouPrice() != null) {
                    totalCost = totalCost.add(course.getCouPrice());
                }
            } else {
                throw new RuntimeException("课程ID " + courseId + " 不存在，交易取消。");
            }
        }

        if (student.getStuScore() < totalCost.longValue()) {
            System.err.println("购买失败：学生总积分不足。所需积分：" + totalCost + ", 当前积分：" + student.getStuScore());
            return false;
        }

        for (Long courseId : courseIds) {
            boolean success = this.purchaseCourse(studentId, courseId);
            if (!success) {
                throw new RuntimeException("课程ID " + courseId + " 购买失败（可能已存在），整个交易已取消。");
            }
        }

        return true;
    }

    public List<Course> getPurchasedCoursesByStudentId(Long studentId) {
        return purchaseRecordMapper.findPurchasedCoursesByStudentId(studentId);
    }
}